var num_element_in_cart;
	var loading=false;
	function show_num_copies(el_id){
		if (loading) return;
		$(".slide_down_copies").fadeOut("fast");
		$("#"+el_id).parent().find(".slide_down_copies").fadeIn("fast");
		}
	
	function hide_num_copies(el_id){
		if (loading) return;
		$("#"+el_id).parents(".slide_down_container").children(".slide_down_copies").fadeOut("fast");
		$("#"+el_id).parent().children(".cart_error").css("display","none");
		}
	function send_book_request(el_id){
		if (loading) return;
		$book_id = $("#"+el_id).parent().children("#book_id").val();
		$num_copies = $("#"+el_id).parent().children("#num_copies_input").val();
		if ( parseInt( $num_copies ) == 0 )
			return ; 
		loading=true;
		
		$("#"+el_id).parent().children(".ajax-loading").css("display" , "none");
		
		
		$.post("ajax.php", 
				{ request_type:"add_book", book_id : $book_id , num_copies : $num_copies  },
				function(data) {
					if (data['error'] != null){
						$("#"+el_id).parent().children(".ajax-loading").fadeOut("slow", function(){
							$(this).parent().children(".cart_error").fadeIn("slow")});
						return;
					}
					else{
						//nessun errore, procedo
						$("#"+el_id).parent().fadeOut("fast");
						$("#"+el_id).parent().find(".ajax-loading").fadeOut("fast");
						
						if ( data['already_in_cart'] != null ){
							
							$("#list_elem_"+data['id'] ).find(".cart_book_num").html("Copie: "+data['num_copies']);
							$("#list_elem_"+data['id']).effect("highlight", {mode:"show"}, 1000);
							$("#"+el_id).parents(".shop-item").find(".newly_added_product").slideDown("slow");
							
						}
						else{
						$("#"+el_id).parents(".shop-item").find(".newly_added_product").slideDown("slow");
							var new_elem = "<li id='list_elem_"+data['id']+"' class='last_item' style='display:none'>\
		        					<p class='cart_book_num'>Copie: "+data['num_copies']+"</p>\
		        					<p class='cart_book_title'>"+data['title']+"</p>\
		        					<p class='cart_book_author_label'>Autore:</p>\
		        					<p class='cart_book_author'>"+data['author']+"</p>\
		        				</li>";
						}
						
						if ( $(".last_item").length > 0 && data['already_in_cart'] == null   ){
							$(".last_item").removeAttr("class").after(new_elem);
	        				$(".last_item").slideDown("slow");
	        				
						}
						else{
							$("#book_list").html(new_elem);
        					$(".last_item").slideDown("slow");
						}
						$("#cart_buttons").slideDown("slow");
						
					}				
												
			 },'json'


		 );
		loading=false;
		num_element_in_cart++;
	}

	function print_cart(){
		$.ajax({
			  url: 'ajax.php',
			  data: {request: "cart"},
		  	 
			  success: function( data ) {
			    alert(data);
			  }
			});
	}

	$("#pagination-form").submit(function(){
		page = $.trim( $("#page_form_num").val() );
		subject = $.trim( $("#hidden-subject").val() );
		if ( page < 1 ||  page > parseInt( $("#hidden-total-pages").val() ) )
			return;
		change_page(page , subject);
	});

	$(".prev").click(function(){
		page =  parseInt ($.trim( $("#page_form_num").val() )) - 1;
		subject = $.trim( $("#hidden-subject").val() ); 

		if ( page < 1 ||  page > parseInt( $("#hidden-total-pages").val() ) )
			return;
		
		change_page(page, subject);
		$("#page_form_num").val(page);
	});


	$(".next").click(function(){
		page = parseInt ($.trim( $("#page_form_num").val() ) ) + 1;
		subject = $.trim( $("#hidden-subject").val() ); 
		
		if ( page < 1 || page > parseInt( $("#hidden-total-pages").val() ) )
			return;
		
		change_page(page, subject);
		$("#page_form_num").val(page);
	});

	$(".next").click(function(){});
	
	$(".positive-integer").numeric({ decimal: false, negative: false }, function() { alert("Positive integers only"); this.value = ""; this.focus(); });

	$("#show_subjects").click(function(){ 
		if ( $("#subject_container").css("display").indexOf("none") != -1 ) 
			$("#arrow").html("&uarr;");
		else
			$("#arrow").html("&darr;");
		$("#subject_container").slideToggle("slow") ;
		
	} );
	
	
	function print_results(data, properties){
		html="";
		
		if (data['have_results'] == true){
			
			
			for(i = 0 ; i< data['results_array'].length ; i++){
				book = data['results_array'][i];
				if ( book['media'] != 1) the_cover="upload/no-cover.jpg";
				else the_cover="upload/covers/"+book['EAN']+".jpg";
				
				html+= '<div class="shop-item ">'+
					'<!--Ribbon-->'+
					'<!-- <span class="out-of-stock"></span>  -->'+
			        ''+
					'<div class="boxgrid slidedown">'+
					'<div class="newly_added_product"><p>Prodotto aggiunto con successo</p></div>'+
					'<h5>'+book['title']+'</h5>'+
					'<div class="covers"><img src="'+the_cover+'"></div>'+  
					'<div class="box-info-container">'+
					'<p class="box_label">Autore</p><p> '+book['author']+'</p>'+
					'<p class="box_label">Editore</p><p> '+book['publisher']+'</p>'+
					'</div>'+
					'</div>'+
					'<!--Item price and button-->'+        
					'<div class="boxgrid-info-box">'+
					'			<a id="show_num_copies_'+book['id']+'" onclick="show_num_copies(this.id)" class="button white-button add">Aggiungi al tuo elenco</a>'+
					'				'+
					'	<div>'+
					'		<input type="hidden" id="num_copies">'+
					'		<div class="slide_down_container">'+
					'			 <div class="slide_down_copies">'+
					'					<label for="num_copies_input">Numero copie</label>'+						 	
					'			 		<input id="num_copies_input" class="positive-integer" type="text" value="1" size="5px" maxlength="3">'+
					'			 		<input type="button" value="Aggiungi" id="send_num_copies_'+book['id']+'" onclick="send_book_request(this.id)">'+
					'			 		<input style="float:right;" id="cancel_num_copies_'+book['id']+'" type="button" onclick="hide_num_copies(this.id)" value="Annulla">'+
					'			 		<input type="hidden" id="book_id" value="'+book['id']+'">'+
					''+			 		
					'			 		<div class="ajax-loading"><img src="images/ajax-loader.gif"><p>Salvataggio in corso</p></div>'+
					'			 		<div class="cart_error"><p>Si è verificato un errore. Riprovare.</p></div>'+
					'			</div>'+  
					''+			
					'		</div>'+
					'	</div>'+
					'</div>'+
					''+		
				'</div>';
				
			}
			
			if (properties['type'] == "search")
				$("#page-description").html("<h5 style='margin-left:10px;'>Risultati di ricerca per: <b>"+properties['query']+"</b></h5>");
				
			else
				$("#page-description").html("<h5 style='margin-left:10px;'>Materia: <b>"+properties['query']+"</b></h5>");
		}
		else{
			$("#page-description").html("<h5 style='margin-left:10px;'>Nessun risultato di ricerca per: <b>"+query+"</b></h5>");
		}
		$("#frontpage").html(html);
		
		
		
	}
	
	
	function change_page(num, subject){
		
		
		
		$("#frontpage").css({ opacity: 0.2 });
		var properties = new Array();
		properties['type']="subject";
		properties['query'] = subject;
		$.ajax({
			  url: 'ajax.php',
			  type: "POST",
			  data: { request_type: "change_page", page_num: num , subject: subject } ,
			  dataType: "json",
			  success: function( data ) {
				  		var stateObj = { foo: "bar" };
						history.pushState(stateObj, "", "index.php?subject="+subject+"&page="+num);
				  		print_results(data, properties);
				  		$("#frontpage").css({ opacity: 1 });
				  		$(".page").removeClass( "current-page" );
				  		$(".pagination_"+num).addClass("current-page");
				  		$("#hidden-current-page").val(num);
			  }
		  	 
			  
			});
		
		
		
	}
	
	
    
	  $("#book_search").submit(function(){
		  
		  $(".pagination").hide();

		  query =  $.trim( $("#book_search_input").val() );
		  
		  var properties = new Array();
		  properties['type'] = "search";
		  properties['query'] = query; 
		  
		  if ( query.length <= 2 ) return;
		  $("#frontpage").css({ opacity: 0.2 });
		  /*$("#searching").html("<p>Ricerca in corso di: <b>"+query+"</b></p>");
		  $("#searching").slideDown("fast");*/
		  $.ajax({
			  url: 'ajax.php',
			  type: "POST",
			  data: { request_type: "search", query: $("#book_search_input").val() } ,
			  dataType: "json",
			  success: function( data ) {
				  		var stateObj = { foo: "bar" };
				  		history.pushState(stateObj, "", "index.php");
				  		print_results(data, properties);
				  		$("#frontpage").css({ opacity: 1 });
				  		
				  		var stateObj = { foo: "bar" };
						history.pushState(stateObj, "", "");
			  }
		  	 
			  
			});
		    
	    });


	  
	
	  $("#empty_cart").click(function() {
			$(".slide_down_copies").fadeOut("fast");
			$(".newly_added_product").slideUp("slow");
			loader = "<img class='loading' src='images/ajax-loader.gif' style='width: 14px; margin-left:5px;'>";
			$(".cart").parent().children(".sidebar-title").append(loader);
			$.ajax({
				  url: 'ajax.php',
				  type: "POST",
				  data: {request_type: "empty_cart"},
				  dataType: "json",
				  success: function( data ) {
					  if( data['empty_cart'] == true){
						  $(".cart").parent().find(".loading").remove();

						  $("#cart_buttons").slideUp("slow");
						  $('#book_list').slideUp("slow" , function(){
						  $("#cart_buttons").slideUp("slow");
						  $(this).html("<p>Elenco vuoto</p>");
						  $(this).slideDown("slow");

				    	
				    });
					  }
				  }
				});
			  
		});

